package cn.edu.sdjzu.xg23.kcsj01_backend.controller;


import cn.edu.sdjzu.xg23.kcsj01_backend.entity.User;
import cn.edu.sdjzu.xg23.kcsj01_backend.entity.authority.Role;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.PermissionService;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.RoleService;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.UserService;
import cn.edu.sdjzu.xg23.kcsj01_backend.utils.JwtUtil;
import cn.edu.sdjzu.xg23.kcsj01_backend.utils.Result;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.edu.sdjzu.xg23.kcsj01_backend.utils.ResultCodeEnum.ROLE_NOT_SELECTED;


@Data
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService  permissionService;


    @PostMapping("/login")
    public Result login(@RequestBody LoginForm form){

        // 校验参数
        if (form.getRoleId() == null) {
            return Result.error(ROLE_NOT_SELECTED);
        }
        // 根据用户名+密码+角色ID查询用户
        User loginUser = userService.loginWithRole(form.getUsername(), form.getPassword(), form.getRoleId());

        if (loginUser != null) {
            // 获取该角色的权限
            List<String> permissions = permissionService.selectPermissionById(form.getRoleId());
            System.out.println("权限列表"+permissions);

            // 不再生成角色列表，直接使用权限生成token
            String token = jwtUtil.generateToken(form.username,permissions);

            // 返回结果
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("user", loginUser);
            resultData.put("token", token);
            resultData.put("roles", roleService.selectRolesByUserId(loginUser.getId()));

            return Result.success(resultData);
        } else {
            return Result.error("500", "用户名、密码或角色错误");
        }
    }
    // 登录表单参数类
    @Data
    public static class LoginForm {
        private String username;
        private String password;
        private Long roleId; // 前端传递的角色ID
    }
}